<?php
require_once 'Translator/Controller.php';

/**
 * UserController for every user related action
 */
class UserController extends Translator_Controller
{
	/**
	 * Sign in action.
	 */
	public function signinAction ()
	{
		if($this->user->isAuthenticated()) {
			$this->_helper->FlashMessenger('You are already signed in!');
			$this->_helper->Redirector('index', 'index');
		}
			
		$sns = new Zend_Session_Namespace('Translator');
			
		// form submitted
		if($this->getRequest()->isPost()) {
			$errors = array();

			$username = trim($this->getRequest()->getPost('username'));
			$password = trim($this->getRequest()->getPost('password'));

			if(empty($username)) {
				$errors[] = 'Please provide a username.';
			}

			if(empty($password)) {
				$errors[] = 'Please provide a password.';
			}

			// just try to login if it could be successful
			if(count($errors) == 0) {
				$result = $this->user->signIn($username, $password);
			}

			if (isset($result) && $result->isValid()) {
				$this->_helper->flashMessenger('You signed in successfully!');

				// redirect to old page if possible
				if(!empty($sns->login_origin)) {
					$origin = $sns->login_origin;
					unset($sns->login_origin);

					$this->_redirect($origin);
				} else {
					$this->_helper->redirector('index', 'index');
				}
			}

			// login failed
			else {
				if(isset($result)) {
					$code = $result->getCode();

					switch($code) {
						case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
						case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
							$errors[] = 'Wrong credentials.';
							break;

						default:
							$errors[] = 'Error while signing in.';
							break;
					}
				}
					
				$this->view->errors = $errors;
			}
		}
			
		// user did not try to login so far, try to save referer
		else {
			// validate referer
			$request = $this->getRequest();
			$server = $request->getScheme().'://'.$this->getRequest()->getHttpHost();

			$origin = $this->getRequest()->getHeader('referer');

			// actually from this server
			if(stripos($origin, $server) === 0) {
				$sns->login_origin = $origin;
			}
		}
			
		if(!isset($this->view->mode)) {
			$this->view->mode = 'signin';
		}
	}

	/**
	 * Become a translator. Basically just a wrapper for the normal
	 * signin action.
	 */
	public function becometranslatorAction() {
		$this->view->mode = 'becometranslator';
		$this->_forward('signin');
		return;
	}

	/**
	 * Sign out action.
	 */
	public function signoutAction()
	{
		// quit without any message if we are not signed in at all
		if(!$this->user->isAuthenticated()) {
			$this->_helper->Redirector('index', 'index');
		}
		 
		$this->user->signOut();
		 
		$this->_helper->FlashMessenger('You are now signed out.');
		$this->_helper->Redirector('index', 'index');
	}

	/**
	 * Request translation privileges.
	 */
	public function applyAction() {
		$this->requireAuthenticated();
		 
		// already translator
		if($this->user->isTranslator()) {
			$this->_helper->FlashMessenger('You are already a translator!');
			$this->_helper->Redirector('index', 'index');
		}
		 
		// request pending
		else if($this->user->isTranslator(true)) {
			$this->_helper->FlashMessenger('You already requested translation privileges, please wait for feedback.');
			$this->_helper->Redirector('index', 'index');
		}
		 
		// user submitted the form
		if($this->getRequest()->isPost()) {
			$name = trim($this->getRequest()->getPost('name'));
			$email = trim($this->getRequest()->getPost('email'));
			$languages = trim($this->getRequest()->getPost('languages'));
			$qualification = trim($this->getRequest()->getPost('qualification'));

			$errors = array();

			if(strlen($name) < 5) {
				$errors[] = 'Please provide a name.';
			}

			require_once 'Zend/Validate/EmailAddress.php';
			$validator = new Zend_Validate_EmailAddress();

			if(empty($email) || !$validator->isValid($email)) {
				$errors[] = 'Please provide a valid e-mail address.';
			}

			if(empty($languages)) {
				$errors[] = 'Please provide languages you want to translate.';
			}

			if(empty($qualification)) {
				$errors[] = 'Please tell us why you are able to perform the translation.';
			}

			// valid form
			if(count($errors) == 0) {
				require_once 'models/UserModel.php';
				$userModel = new UserModel();
					
				require_once 'models/ApplicationModel.php';
				$applicationModel = new ApplicationModel();
					
				// update profile with new data
				$userModel->updateProfile($this->user->id, $name, $email);
					
				// create new application
				$id = $applicationModel->apply($this->user->id, $languages, $qualification);
					
				// inform staff
				$view = $this->getHelper('ViewRenderer')->view;
				$view->id = $id;
				$text = $view->render('mail/application-notification.phtml');
				$mail = new Zend_Mail();
				
				$mail->setFrom('webmaster@geogebra.org', 'GeoGebra Webmaster');
				$mail->addTo('translation@geogebra.org', 'GeoGebra Translation');
				$mail->setSubject('Application for Translator Position');
				$mail->setBodyText($text, 'utf-8');
				$mail->send();
				
				$this->_helper->FlashMessenger('Thank you for applying. We will contact you as soon as possible.');
				$this->_helper->Redirector('index', 'index');
			}

			// invalid form, display error messages
			else {
				$this->view->errors = $errors;
				$this->view->name = $name;
				$this->view->email = $email;
				$this->view->languages = $languages;
				$this->view->qualification = $qualification;
			}
		}
		 
		// pre-fill fields form
		else {
			$this->view->name = $this->user->name;
			$this->view->email = $this->user->email;
			$this->view->languages = '';
			$this->view->qualification = '';
		}
	}
	
	/**
	 * Manage users (administrators only).
	 */
	public function manageAction() {
		$this->requireAdmin();
		
		require_once 'models/ApplicationModel.php';
		$applicationModel = new ApplicationModel();
		
		$this->view->applications = $applicationModel->fetchApplications();
	}
	
	/**
	 * View and decide about individual applications.
	 * Enter description here ...
	 */
	public function applicationAction() {
		$this->requireAdmin();
		
		$id = intval($this->_getParam('id', 0));
		
		require_once 'models/ApplicationModel.php';
		$applicationModel = new ApplicationModel();
		
		$application = $applicationModel->fetchApplication($id);
		
		if(empty($application)) {
			$this->_forward('error404', 'error');
			return;
		}
		
		$this->view->application = $application;
		
		// user decided about what to do
		if($this->getRequest()->isPost()) {
			$accept = $this->getRequest()->getPost('accept');
			$decline = $this->getRequest()->getPost('decline');
			
			/* exactly one parameter is empty and exactly one is not,
			 * otherwise this is not regarded as valid request (the normal
			 * page is displayed) */
			if(empty($accept) xor empty($decline)) {
				// accept application
				if(empty($decline)) {
					$userlanguages = $this->getRequest()->getPost('languages');

					require_once 'models/LanguageModel.php';
					$languageModel = new LanguageModel();
					$languages = $languageModel->fetchLanguages();
					
					// validate languages by comparing them with db results
					if(!empty($userlanguages)) {
						if(!is_array($userlanguages)) {
							$userlanguages = null;
						} else {
							$languages_ids = array();
							
							foreach($languages as $lang) {
								$languages_ids[] = $lang->id;
							}
							
							foreach($userlanguages as $lang) {
								/* compare user selection with languages in the database,
								 * if just one value does not match a db row ignore all
								 * values */
								if(!in_array($lang, $languages_ids)) {
									$userlanguages = null;
									break;
								}
							}
						}
					}
					
					/* still in first step, display second step form to let the
					 * user choose the languages */
					if(empty($userlanguages) || count($userlanguages) == 0) {
						$this->_helper->viewRenderer('application-accept');
						$this->view->languages = $languages;
					}
					
					/* user already chose languages, promote user to translator
					 * and save selection */
					else {
						$languageModel->saveUserLanguages($application->user, $userlanguages);
						$applicationModel->removeApplication($id, $application->user, true);
						
						// selected languages as text
						$userlanguages_str = array();
						
						foreach($languages as $lang) {
							if(in_array($lang->id, $userlanguages)) {
								$userlanguages_str[] = $lang->name;
							}
						}
						
						// inform user by e-mail
						$view = $this->getHelper('ViewRenderer')->view;
						$view->name = $application->name;
						$view->message = $this->getRequest()->getPost('message');
						$view->languages = $userlanguages_str;
						$text = $view->render('mail/application-accepted.phtml');
						$mail = new Zend_Mail();
						
						$mail->setFrom('webmaster@geogebra.org', 'GeoGebra Webmaster');
						$mail->addTo($application->email, $application->name);
						$mail->setSubject('Application as GeoGebra Translator Accepted');
						$mail->setBodyText($text, 'utf-8');
						$mail->send();
						
						$this->_helper->FlashMessenger('Application accepted and user informed.');
						$this->_helper->Redirector('manage', 'user');
					}
				}
				
				// reject application
				else {
					$message = $this->getRequest()->getPost('message');
					
					if(empty($message)) {
						$this->_helper->viewRenderer('application-decline');
					} else {					
						$applicationModel->removeApplication($id, $application->user, false);
						
						// inform user by e-mail
						$view = $this->getHelper('ViewRenderer')->view;
						$view->name = $application->name;
						$view->message = $this->getRequest()->getPost('message');
						$text = $view->render('mail/application-rejected.phtml');
						$mail = new Zend_Mail();
						
						$mail->setFrom('webmaster@geogebra.org', 'GeoGebra Webmaster');
						$mail->addTo($application->email, $application->name);
						$mail->setSubject('Application as GeoGebra Translator Rejected');
						$mail->setBodyText($text, 'utf-8');
						$mail->send();
						
						$this->_helper->FlashMessenger('Application rejected.');
						$this->_helper->Redirector('manage', 'user');
					}
				}
			}
		}
	}
}
